import { EggAppConfig, EggAppInfo, PowerPartial } from "egg";
import * as path from "path";

export default (appInfo: EggAppInfo): PowerPartial<EggAppConfig> => {
  const config: PowerPartial<EggAppConfig> = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + "_charity_platform_2024";

  // 中间件
  config.middleware = [];

  // 用户自定义配置
  const userConfig = {
    // myAppName: 'egg',
  };

  // 跨域配置
  config.cors = {
    origin: "*",
    allowMethods: "GET,HEAD,PUT,POST,DELETE,PATCH",
    credentials: true,
  };

  // JWT配置
  config.jwt = {
    secret: "charity_platform_jwt_secret",
    // 忽略无需验证的路径（已添加 /api 前缀）
    ignore: ["/api/auth/login", "/api/auth/register", "/public", "/api/health"],
  };

  // 数据库配置
  config.sequelize = {
    dialect: "mysql",
    host: process.env.DB_HOST || "localhost",
    port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 3306,
    database: process.env.DB_NAME || "charity_platform",
    username: process.env.DB_USER || "root",
    password: process.env.DB_PASSWORD || "123456",
    timezone: "+08:00",
    define: {
      freezeTableName: true,
      underscored: true,
      charset: "utf8mb4",
      collate: "utf8mb4_unicode_ci",
    },
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
  };

  // Redis配置
  config.redis = {
    client: {
      port: process.env.REDIS_PORT || 6379,
      host: process.env.REDIS_HOST || "127.0.0.1",
      password: process.env.REDIS_PASSWORD || "",
      db: 0,
    },
  };

  // 文件上传配置
  config.multipart = {
    mode: "file",
    fileExtensions: [".jpg", ".jpeg", ".png", ".gif", ".pdf", ".doc", ".docx"],
    fileSize: "10mb",
  };

  // 安全配置
  config.security = {
    csrf: {
      enable: false,
    },
    domainWhiteList: ["http://localhost:3000", "http://127.0.0.1:3000"],
  };

  // 静态资源配置
  config.static = {
    prefix: "/public/",
    dir: path.join(appInfo.baseDir, "app/public"),
  };

  // 日志配置
  config.logger = {
    level: "INFO",
    consoleLevel: "INFO",
  };

  // Web3配置
  config.web3 = {
    provider:
      process.env.WEB3_PROVIDER ||
      "https://sepolia.infura.io/v3/YOUR_INFURA_KEY",
    contractAddress: process.env.CONTRACT_ADDRESS || "",
  };

  return {
    ...config,
    ...userConfig,
  };
};
